package com.keon.jianbao.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.AppManager;
import com.keon.jianbao.R;
import com.keon.jianbao.adapter.UploadImgAdapter;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Appraisal;
import com.keon.jianbao.bean.Expert;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.ui.widget.NoScrollGridView;
import com.keon.jianbao.util.DialogHelp;
import com.keon.jianbao.util.ImageUtils;
import com.keon.jianbao.util.JsonUtils;
import com.keon.jianbao.util.StringUtils;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by keon on 2015/9/21.
 */
public class UploadJianBaoActivity extends BaseActivity {


    public static final int REQUEST_PICK_PHOTO = 1;
    public static final int MAX_UPLOAD_IMAGE_NUM = 8;

    UploadImgAdapter adapter;
    ArrayList<String> uploadImgs;

    String[] catlogs;
    String selectedCatlog;
    String[] ages;
    String selectedAge;
    Expert expert = null;
    Appraisal appraisal = null;

    int indexCatlog = 0;
    int indexAge = 0;

    @Bind(R.id.appraisalName)
    EditText etName;
    @Bind(R.id.appraisalCatlog)
    Button bCatlog;
    @Bind(R.id.appraisalAge)
    Button bAge;
    @Bind(R.id.appraisalSize)
    EditText etSize;
    @Bind(R.id.appraisalWeight)
    EditText etWeight;
    @Bind(R.id.appraisalDesc)
    EditText etDesc;
    @Bind(R.id.upload_jianbao_image)
    NoScrollGridView nsgvImage;
    @Bind(R.id.upload_jianbao_submit)
    Button bSubmit;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    hideWaitDialog();
                    adapter.updateData(uploadImgs);
                    break;
            }
        }
    };

    SimpleHandler catlogHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    ArrayList<String> t_catlogs = JsonUtils.fromJson(result.getContent(), ArrayList.class);
                    catlogs = new String[t_catlogs.size()];
                    for (int i = 0; i < t_catlogs.size(); i++) {
                        catlogs[i] = t_catlogs.get(i);
                    }

                    bCatlog.setText(catlogs[0]);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler ageHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    ArrayList<String> t_ages = JsonUtils.fromJson(result.getContent(), ArrayList.class);
                    t_ages.add("其他");
                    ages = new String[t_ages.size()];
                    for (int i = 0; i < t_ages.size(); i++) {
                        ages[i] = t_ages.get(i);
                    }
                    bAge.setText(ages[0]);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler uploadImagesHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    JSONArray ja = new JSONArray(new JSONObject(result.getContent()).getString("images"));
                    String[] images = new String[ja.length()];
                    for (int i = 0; i < ja.length(); i++) {
                        images[i] = ja.get(i).toString();
                    }

                    Api.appraisal_add(expert, etName.getText().toString(), bCatlog.getText().toString(), etSize.getText().toString(),
                            etWeight.getText().toString(), bAge.getText().toString(), etDesc.getText().toString(),
                            images, appraisalAddHandler);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler appraisalAddHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                showToast(result.getTips());
                if (result.getStatus() > 0) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("expert", expert);
                    bundle.putSerializable("appraisal", appraisal);
                    bundle.putInt("appraisal_id",
                            Integer.parseInt(JsonUtils.fromJson(result.getContent(), HashMap.class).get("appraisal_id").toString()));

                    jump(JianBaoPayWayActivity.class, bundle);
                    AppManager.getAppManager().finishActivity(UploadJianBaoActivity.class);
                    AppManager.getAppManager().finishActivity(ListActivity.class);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_upload_jianbao;
    }

    @Override
    protected int getToolBarTitle() {
        return R.string.upload_jianbao;
    }

    @Override
    public void initView() {
        bSubmit.setOnClickListener(this);
        bCatlog.setOnClickListener(this);
        bAge.setOnClickListener(this);

        initGridView();

    }

    @Override
    public void initData() {
        catlogHandler.setContext(this);
        ageHandler.setContext(this);
        uploadImagesHandler.setContext(this);
        appraisalAddHandler.setContext(this);

        showWaitDialog();
        Api.appraisal_catalog(catlogHandler);
        Api.appraisal_age(ageHandler);

        Bundle bundle = getIntent().getExtras();
        expert = (Expert) bundle.getSerializable("expert");
        if (expert == null) {
            showToast(R.string.common_error_network);
            onBackPressed();
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.appraisalCatlog:
                if (catlogs.length > 0) {
                    DialogHelp.getSingleChoiceDialog(this, catlogs, indexCatlog, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            indexCatlog = i;
                            selectedCatlog = catlogs[i];
                            bCatlog.setText(selectedCatlog);

                        }
                    }).show();
                } else {
                    showToast(R.string.common_error_network);
                    onBackPressed();
                }
                break;
            case R.id.appraisalAge:
                if (ages.length > 0) {
                    DialogHelp.getSingleChoiceDialog(this, ages, indexAge, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            indexAge = i;
                            if (ages[i].equals("其他")) {
                                dialogInterface.dismiss();
                                final EditText et = new EditText(UploadJianBaoActivity.this);
                                et.setTextColor(UploadJianBaoActivity.this.getResources().getColor(R.color.textColor));
                                new AlertDialog.Builder(UploadJianBaoActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert).setTitle("请输入藏品质地")
                                        .setView(et)
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
//                                                catlogs[catlogs.length] = et.getText().toString();
                                                selectedAge = et.getText().toString();

                                                if (StringUtils.isEmpty(selectedAge)) {
                                                    showToast("藏品质地不能为空");
                                                    bAge.setText(ages[0]);
                                                    indexAge = 0;
                                                } else {
                                                    bAge.setText(selectedAge);
                                                }
                                            }
                                        })
                                        .setNegativeButton("取消", null).show();

                            } else {
                                selectedAge = ages[i];
                                bAge.setText(selectedAge);

                            }
                        }
                    }).show();
                } else {
                    showToast(R.string.common_error_network);
                    onBackPressed();
                }
                break;
            case R.id.upload_jianbao_submit:
                if (check()) {
                    try {
                        File[] imgs = new File[uploadImgs.size()];
                        for (int i = 0; i < uploadImgs.size(); i++) {
                            imgs[i] = new File(uploadImgs.get(i));
                        }
                        showWaitDialog();
                        Api.upload_appraisal_images(AppContext.getInstance().getProperty("user.code"), imgs, uploadImagesHandler);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_PICK_PHOTO:
//                ArrayList<String> images = data.getStringArrayListExtra(Constant.EXTRA_PHOTO_PATHS);
                final ArrayList<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);

                Thread t = new Thread() {
                    @Override
                    public void run() {
//                        super.run();
                        try {
                            uploadImgs = ImageUtils.getCompressImages(images);
                            handler.sendEmptyMessage(1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                };
                showWaitDialog("压缩图片中");
                t.start();

       /*         try {
                    uploadImgs = ImageUtils.getCompressImages(images);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                adapter.updateData(uploadImgs);*/
//                mAdaper.swapDatas(images);
                break;
        }
    }

    private void initGridView() {
        adapter = new UploadImgAdapter(MAX_UPLOAD_IMAGE_NUM);

        nsgvImage.setAdapter(adapter);
    }


    private boolean check() {

        if (uploadImgs != null && uploadImgs.size() > 0) {
        } else {
            showToast(R.string.upload_jianbao_image_error_null);
            return false;
        }
        if (StringUtils.isEmpty(etName.getText().toString())) {
            showToast(R.string.upload_jianbao_name_tip);
            return false;
        }
        if (StringUtils.isEmpty(etSize.getText().toString())) {
            showToast(R.string.upload_jianbao_size_tip);
            return false;
        }
        if (StringUtils.isEmpty(etWeight.getText().toString())) {
            showToast(R.string.upload_jianbao_weight_tip);
            return false;
        }
        if (StringUtils.isEmpty(etDesc.getText().toString())) {
            showToast(R.string.upload_jianbao_description_tip);
            return false;
        }

        appraisal = new Appraisal(etName.getText().toString(), bCatlog.getText().toString(), etDesc.getText().toString(), uploadImgs);

        return true;
    }
}
